package com.suse.lhw.hms.authserver.handler;

import com.suse.lhw.hms.authserver.constan.ResultCode;
import com.suse.lhw.hms.authserver.tools.ResUtil;
import com.suse.lhw.hms.authserver.tools.ResponseUtil;
//import com.suse.lhw.hms.authserver.tools.TokenUtil;
import com.suse.lhw.hms.authserver.tools.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @ProjectName: health_manage_system
 * @Package: com.suse.lhw.hms.authserver.config
 * @ClassName: SuccsseAuthorizaionHandler
 * @Description: java类作用描述
 * @Author: 李鸿炜
 * @CreateDate: 2020/4/2 9:19
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/4/2 9:19
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Component
public class SuccsseAuthorizaionHandler implements AuthenticationSuccessHandler {

    protected Logger logger = LoggerFactory.getLogger(getClass());
    //构造方法注册tokenUtil避免发生循坏认证
    @Resource
    private TokenUtil tokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        /**
         * @Author:Hongwei Li
         * @Description:使用token的形式来存储用户信息
         * @Date:15:03 2020/4/9
         * @Param:[httpServletRequest, httpServletResponse, authentication]
         * @Return:void
         **/
        //UserDetails uu= (UserDetails) authentication.getPrincipal();
        //AuthUserDetail userDetail= (AuthUserDetail) authentication.getPrincipal();
        User principal = (User) authentication.getPrincipal();
        String username = principal.getUsername();
        //创建token
        String accessToken = tokenUtil.createAccessJwtToken(username);
        String refreshToken = tokenUtil.createRefreshToken(username);
        HashMap<String, String> map = new HashMap<>();
        map.put("accessToken", accessToken);
        map.put("refreshToken", refreshToken);
        System.out.println("登录成功");
        httpServletResponse.getWriter().write("終於進來了");
        ResponseUtil.out(httpServletResponse, ResUtil.getJsonStr(ResultCode.OK, "登录成功", map));
    }
}
